//
//  XYVoiceRecognizeManager.swift
//  XuYiAgriculture
//
//  Created by 宋海胜 on 2020/11/23.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit

protocol XYVoiceRecognizeProtocol {
    func voiceContent(content: String)
}

class XYVoiceRecognizeManager: NSObject {
    
    var currentVC: UIViewController?
    var delegate: XYVoiceRecognizeProtocol?
    var iFlySpeechRecognizer = IFlySpeechRecognizer()
    var typeNumber: NSInteger  = 0
    let voiceImage: UIImageView = {
        let v = UIImageView(image: UIImage(named: "voice_default"))
        v.isUserInteractionEnabled = true
        return v
    }()
    let voiceImageBackView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(white: 0, alpha: 0.5)
        v.layer.cornerRadius = 5
        v.layer.masksToBounds = true
        return v
    }()
    
    init(currentVC: UIViewController) {
        super.init()
        self.currentVC = currentVC
        self.currentVC!.view.addSubview(voiceImageBackView)
        self.voiceImageBackView.isHidden = true
        voiceImageBackView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.height.equalTo(150)
            make.width.equalTo(150)
        }
        
        voiceImageBackView.addSubview(voiceImage)
        voiceImage.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.height.equalTo(63.5)
            make.width.equalTo(81.5)
        }
    }
    
    //语音识别
    func startIFlySpeechRecognize() {
        
        ASRConfig.shared.starIdentify()
        ASRConfig.shared.resultClosure = {[weak self] (type, error, res) in
            
            print("strResutl: \(type) %\(String(describing: error)) res:\(res)")
            if let weakSelf = self {
                
                switch type {
                case .IFTypeCancel:
                    print("项目调试 语音识别取消");
                    break;
                    
                case .IFTypeiniting:
                    print("项目调试 语音正在识别中");
                    self?.voiceImageBackView.isHidden = false
                    
                    ASRConfig.shared.blockOnVolumeChanged = {volume in
                        weakSelf.getVoiceNum(num: Float(volume)/5)
                    }
                    break;
                    
                case .IFTypeStart:
                    print("项目调试 语音识别开始");
                    break;
                    
                case .IFTypeStop:
                    print("项目调试 语音识别Stop");
                    break;
                    
                case .IFTypeEnd:
                    print("项目调试 语音识别End");
                    do {
                        self?.voiceImageBackView.isHidden = true
                        if res.contains("退出") {
                            self?.stopIFlySpeechRecognize()
                        }else{
                            // 如果是空字符串, 自动提示指令语音
                            if (weakSelf.YQStringIsEmpty(value: res as AnyObject)) {
                                weakSelf.typeNumber+=1;
                                // 检测回调次数，提示大于3次则自动退出
                                if (weakSelf.typeNumber > 2) {
                                    self?.stopIFlySpeechRecognize();
                                    return;
                                    
                                }else{
                                    let notice: String = "您好像没有说话"
                                    SynthesizerModel.shared.startSpeak(speak: notice)
                                }
                            } else {
                                //流程: 识别出结果， 开始请求接口， 并重新计数
                                weakSelf.typeNumber = 0;    // 重新计数
                                self?.getData(textContent: res);   // 请求接口
                            }
                        }
                    }
                    break;
                }
            }
        }
    }
    
    func getVoiceNum(num: Float) {
        var i = 0
        if num <= 1 {
            i = 0
        } else if num > 1 && num <= 2 {
            i = 1
        } else if num > 2 && num <= 3 {
            i = 2
        } else if num > 3 && num <= 4 {
            i = 3
        } else if num > 4 {
            i = 4
        }
        self.voiceImage.image = UIImage(named: "voice\(i)")
    }
    
    func stopIFlySpeechRecognize(){
        print("XYVoiceRecognizeProtocol 语音识别 stopIFlySpeechRecognize");
        ASRConfig.shared.stopIdentify()
        SynthesizerModel.shared.stopSpeak()
    }
    
    //value 是AnyObject类型是因为有可能所传的值不是String类型，有可能是其他任意的类型。
    func YQStringIsEmpty(value: AnyObject?) -> Bool {
        
        //首先判断是否为nil
        if (nil == value) {
            //对象是nil，直接认为是空串
            return true
        }else{
            //然后是否可以转化为String
            if let myValue  = value as? String{
                //然后对String做判断
                return myValue == "" || myValue == "(null)" || 0 == myValue.count
            }else{
                //字符串都不是，直接认为是空串
                return true
            }
        }
    }
    
    func getData(textContent: String?){
        print("项目调试 识别内容：\(textContent ?? "")")
        if (!self.YQStringIsEmpty(value: textContent as AnyObject)) {
            self.delegate?.voiceContent(content: textContent ?? "")
        }
    }
    
}
